package dgut.bbm.service.impl;

import dgut.bbm.dao.GoodsDao;
import dgut.bbm.entity.GoodsEntity;
import dgut.bbm.service.GoodsService;
import dgut.bbm.to.ForOrderTo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;
import java.util.UUID;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import dgut.bbm.common.utils.PageUtils;
import dgut.bbm.common.utils.Query;

import dgut.bbm.dao.GoodsOrderDao;
import dgut.bbm.entity.GoodsOrderEntity;
import dgut.bbm.service.GoodsOrderService;

import javax.annotation.Resource;


@Service("goodsOrderService")
public class GoodsOrderServiceImpl extends ServiceImpl<GoodsOrderDao, GoodsOrderEntity> implements GoodsOrderService {

    @Resource
    GoodsDao goodsDao;

    @Autowired
    GoodsService goodsService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<GoodsOrderEntity> page = this.page(
                new Query<GoodsOrderEntity>().getPage(params),
                new QueryWrapper<GoodsOrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public GoodsOrderEntity generateOrder(ForOrderTo forOrderTo) {
//        private Long  goodsId;
//        private Integer quantity;
//        private BigDecimal goodsPrice;
//        private Long userId;

        //1.价格校验
        //2.查库存，锁库存。
        GoodsOrderEntity goodsOrderEntity=new GoodsOrderEntity();
        GoodsEntity goodsEntity =goodsService.getById(forOrderTo.getGoodsId());
        Long count=0l;
        if(goodsEntity.getStock()-goodsEntity.getStockLocked()>=forOrderTo.getQuantity())
        {
            count=goodsDao.lockStock(forOrderTo.getGoodsId(),forOrderTo.getQuantity(),forOrderTo.getGoodsPrice());
        }
        if(count>=1){
            goodsOrderEntity.setUserId(forOrderTo.getUserId());
            goodsOrderEntity.setQuantity(forOrderTo.getQuantity());
            goodsOrderEntity.setGoodsId(forOrderTo.getGoodsId());
            goodsOrderEntity.setTotalPrice(goodsEntity.getPrice().multiply(new BigDecimal(forOrderTo.getQuantity().toString())));
            goodsOrderEntity.setPayStatus(0);
            String OrderSn= UUID.randomUUID().toString().replace("-","").substring(30);
            goodsOrderEntity.setOrderSn(OrderSn);
            this.baseMapper.insert(goodsOrderEntity);
            goodsOrderEntity=baseMapper.selectById(goodsOrderEntity.getId());
        }
        //3.生成订单

        return goodsOrderEntity;
    }

}